import {
	defineStore
} from 'pinia';
import {
	baseAPI
} from '@/api/index';

const getWxCode = () => {
	return new Promise((resolve, reject) => {
		wx.login({
			success: (wxRes) => {
				resolve(wxRes.code)
			}
		})
	})
}

const getAccessData = (code) => {
	return new Promise((resolve, reject) => {
		baseAPI.post('auth/mnpLogin', {
			code
		}).then(res => {
			resolve(res.result);
		})
	})
}


export const useUserStore = defineStore('user', {
	state: () => {
		return {
			messageStats: null,
			token: uni.getStorageSync('token') || null,
			userInfo: uni.getStorageSync('userInfo') || null
		};
	},
	actions: {
		// 设置token
		setToken(token) {
			this.token = token;
			uni.setStorageSync('token', token);
		},
		// 设置用户信息
		setUserInfo(userInfo) {
			this.userInfo = userInfo;
			uni.setStorageSync('userInfo', userInfo);
		},
		// 保存登录信息
		login(loginData) {
			if (loginData.token) {
				this.setToken(loginData.token);
			}

			if (loginData.user) {
				this.setUserInfo(loginData.user);
			}
		},
		// 退出登录
		logout() {
			this.token = null;
			this.userInfo = null;
			this.messageStats = null;
			uni.removeStorageSync('token');
			uni.removeStorageSync('userInfo');
		},
		async mnpLogin() {
			const code = await getWxCode();
			const accessData = await getAccessData(code);
			this.login(accessData);
			return accessData
		}
	}
});